<?php

require './upload.php';

class Server
{
	const HOST = '0.0.0.0';
	const PORT = 9527;

	const OSS_KEY = '';
	const OSS_SECRET = '';

	public $upload = null;

	private $ws = null;
	private $set = [
		'document_root' => '/root/Chat/Server/', // v4.4.0以下版本, 此处必须为绝对路径
		'enable_static_handler' => true,
	];

	// 已连接客户端
	private $client_list = [];
	// 在线用户信息
	private $on_line_list = [];
	
	public function __construct()
	{
		$this->ws = new Swoole\Websocket\server(self::HOST, self::PORT);
        $this->ws->set($this->set);
        $this->ws->on('open', [$this, 'open']);
        $this->ws->on('close', [$this, 'close']);
        $this->ws->on('message', [$this, 'message']);
        $this->ws->on('request', [$this, 'request']);

        $this->upload = new FileUpload();
        $this->upload->set("path", './Upload');
        $this->upload->set("israndname", true);
        $this->upload->set("allowtype", ['jpg', 'png', 'gif', 'jpeg']);

		$this->ws->start();
	}


	/**
	 * 建立连接，上线
	 */
	public function open(Swoole\Websocket\server $server, $request)
	{
		echo "{$request->fd} 连接" . PHP_EOL;
	}


	/**
	 * 断开
	 */
	public function close(swoole_websocket_server $serv, $fd)
	{
		// 上传文件
		if (!isset($this->on_line_list[$fd])) {
			return false;
		}

		$this->send(-$fd, [
			'event' => 'logout',
			'from' => $this->on_line_list[$fd]
		]);

		echo "{$fd} 断开" . PHP_EOL;
		$uuid = $this->on_line_list[$fd]['uuid'];
		unset($this->client_list[$uuid]);
		unset($this->on_line_list[$fd]);
	}


	public function login($data, $fd)
	{
		// 告诉他已在线人员
		$this->send($fd, [
			'event' => 'online',
			'data' => array_values($this->on_line_list)
		]);
		// 通知其他在线客户本人上线
		$data['event'] = 'login';
		$this->send(-$fd, $data);

		$this->client_list[$data['from']['uuid']] = $fd;
		$this->on_line_list[$fd] = $data['from'];
	}
	
	/**
	 * 收到消息
	 */
	public function message(Swoole\Websocket\server $server, $frame)
	{
		$data = json_decode($frame->data, true);
		switch ($data['event']) {
			case 'login' :
				$this->login($data, $frame->fd);
				break;
			case 'logout' :
				$this->logout($data, $frame->fd);
				break;
            case 'msg' :
                if ($data['to'] < 0) {
                    $fd = -$this->client_list[-$data['to']];
                } else {
                    $fd = $this->client_list[$data['to']];
                }
                $this->send($fd, $data);
				break;
		}
	}


	/**
	 * 发送消息
	 */
	public function send($fd = 0, $content = '')
	{
		// 除了fd外所有人
		if ($fd < 0) {
			foreach ($this->client_list as $val) {
				if ($val != -$fd) {
					$this->ws->push($val, json_encode($content));
				}
			}
		// 所有人
		} elseif ($fd == 0) {
			foreach ($this->client_list as $val) {
				$this->ws->push($val, json_encode($content));
			}
		// 单个人
		} else {
			$this->ws->push($fd, json_encode($content));
		}
    }
    

    /**
     * 
     */
    public function request($request, $response)
    {
        $_FILES = $request->files;
        if ($this->upload->upload('image')) {
            $res = [
                'status' => 1,
                'fileName' => 'Upload/' . $this->upload->getFileName()
            ];
        } else {
            $res = [
                'status' => 1,
                'msg' => $this->upload->getErrorMsg()
            ];
				}
				echo $this->upload->getFileName() . PHP_EOL;
        $response->header('Access-Control-Allow-Origin', '*', true);
        $response->header('Access-Control-Allow-Methods', 'POST,GET,OPTIONS,DELETE', true);
        $response->header('Access-Control-Allow-Credentials', 'true', true);
        $response->header('Access-Control-Allow-Headers', 'Content-Type,Content-Length,Accept-Encoding,X-Requested-with, Origin', true);
        $response->header('Content-Type', 'text/json; charset=utf-8', true);
        $response->end(json_encode($res));
        // $response->end('233');
    }

}

new Server();
